<template>
  <div class="profile-settings">
    <!-- 头部栏 -->
    <HeaderComponent 
      :isLoggedIn="isLoggedIn"
      :userInfo="userInfo"
      :showUserPanel="showUserPanel"
      @open-login="$emit('open-login')"
      @toggle-user-panel="$emit('toggle-user-panel')"
      @logout="$emit('logout')"
    />
    
    <!-- 主布局 -->
    <div class="main-layout">
      <!-- 左侧设置导航栏 -->
      <aside class="settings-sidebar">
        <div class="sidebar-header">
          <h3>设置</h3>
        </div>
        <ul class="settings-nav">
          <li class="nav-item active">
            <router-link to="/user/settings/profile" class="nav-link">
              <span class="nav-icon">👤</span>
              <span>个人资料</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/user/settings/account" class="nav-link">
              <span class="nav-icon">🔐</span>
              <span>账号设置</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/user/settings/general" class="nav-link">
              <span class="nav-icon">⚙️</span>
              <span>通用设置</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/user/settings/notifications" class="nav-link">
              <span class="nav-icon">🔔</span>
              <span>消息设置</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/user/settings/block" class="nav-link">
              <span class="nav-icon">🚫</span>
              <span>屏蔽管理</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/user/settings/tags" class="nav-link">
              <span class="nav-icon">🏷️</span>
              <span>标签管理</span>
            </router-link>
          </li>
        </ul>
      </aside>
      
      <!-- 右侧内容区 -->
      <main class="settings-content">
        <div class="settings-header">
          <h2>个人资料</h2>
          <p>管理您的个人信息和公开资料</p>
          <div class="header-actions">
            <button 
              class="btn-refresh" 
              @click="loadProfile" 
              :disabled="loading || !isLoggedIn"
              title="刷新用户信息"
            >
              {{ loading ? '加载中...' : '刷新数据' }}
            </button>
          </div>
        </div>
        
        <!-- 未登录提示 -->
        <div v-if="!isLoggedIn" class="login-prompt">
          <div class="prompt-icon">🔒</div>
          <h3>请先登录</h3>
          <p>您需要登录后才能查看和编辑个人信息</p>
          <button class="btn-login" @click="$emit('open-login')">
            立即登录
          </button>
        </div>
        
        <!-- 个人信息表单 -->
      <div v-else class="form-section">
        <h3>基本信息</h3>
        <div class="form-row">
          <div class="form-group">
            <label>账号</label>
            <input type="text" v-model="profile.userAccount" placeholder="用户账号" readonly />
          </div>
          
          <div class="form-group">
            <label>昵称 <span class="editable-mark">*</span></label>
            <input type="text" v-model="profile.nickname" placeholder="请输入昵称" />
          </div>
        </div>
        
        <div class="form-group">
          <label>头像URL <span class="editable-mark">*</span></label>
          <input type="url" v-model="profile.userAvatar" placeholder="请输入头像链接" />
          <div v-if="profile.userAvatar" class="avatar-preview">
            <img :src="profile.userAvatar" alt="头像预览" @error="handleImageError" />
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label>邮箱</label>
            <input type="email" v-model="profile.email" placeholder="请输入邮箱" readonly />
          </div>
          
          <div class="form-group">
            <label>手机号</label>
            <input type="tel" v-model="profile.phone" placeholder="请输入手机号" readonly />
          </div>
        </div>
      </div>
      
      <div class="form-section">
        <h3>工作信息</h3>
        <div class="form-row">
          <div class="form-group">
            <label>职位 <span class="editable-mark">*</span></label>
            <input type="text" v-model="profile.position" placeholder="请输入职位" />
          </div>
          
          <div class="form-group">
            <label>公司 <span class="editable-mark">*</span></label>
            <input type="text" v-model="profile.company" placeholder="请输入公司" />
          </div>
        </div>
        
        <div class="form-group">
          <label>地址 <span class="editable-mark">*</span></label>
          <input type="text" v-model="profile.location" placeholder="请输入地址" />
        </div>
      </div>
      
      <div class="form-section">
        <h3>社交链接</h3>
        <div class="form-group">
          <label>个人网站 <span class="editable-mark">*</span></label>
          <input type="url" v-model="profile.website" placeholder="请输入个人网站" />
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label>GitHub <span class="editable-mark">*</span></label>
            <input type="url" v-model="profile.githubUrl" placeholder="请输入GitHub链接" />
          </div>
          
          <div class="form-group">
            <label>微博 <span class="editable-mark">*</span></label>
            <input type="url" v-model="profile.weiboUrl" placeholder="请输入微博链接" />
          </div>
        </div>
      </div>
      
      <div class="form-section">
        <h3>个人简介</h3>
        
        <div class="form-group">
          <label>个人介绍 <span class="editable-mark">*</span></label>
          <textarea 
            v-model="profile.userProfile" 
            placeholder="请输入个人简介" 
            rows="4"
            maxlength="500"
          ></textarea>
          <div class="char-count">{{ (profile.userProfile || '').length }}/500</div>
        </div>
      </div>
      
      <div class="form-section">
        <h3>账号信息</h3>
        <div class="form-group">
          <label>用户角色</label>
          <input type="text" v-model="profile.userRole" placeholder="用户角色" readonly />
        </div>
        
        <div class="form-group">
          <label>账号状态</label>
          <input type="text" :value="profile.status === 0 ? '正常' : '异常'" readonly />
        </div>
        
        <div class="form-group">
          <label>邮箱验证状态</label>
          <input type="text" :value="profile.emailVerified === 1 ? '已验证' : '未验证'" readonly />
        </div>
        
        <div class="form-group">
          <label>手机验证状态</label>
          <input type="text" :value="profile.phoneVerified === 1 ? '已验证' : '未验证'" readonly />
        </div>
        
        <div class="form-group">
          <label>注册时间</label>
          <input type="text" :value="profile.createTime" readonly />
        </div>
        
        <div class="form-group">
          <label>最后登录</label>
          <input type="text" :value="profile.lastLogin" readonly />
        </div>
      </div>
      
      <div class="form-section">
        <h3>统计数据</h3>
        <div class="stats-grid">
          <div class="stat-item">
            <label>掘金力量</label>
            <div class="stat-value">{{ profile.juejinPower }}</div>
          </div>
          
          <div class="stat-item">
            <label>用户等级</label>
            <div class="stat-value">Lv.{{ profile.level }}</div>
          </div>
          
          <div class="stat-item">
            <label>粉丝数</label>
            <div class="stat-value">{{ profile.followerCount }}</div>
          </div>
          
          <div class="stat-item">
            <label>关注数</label>
            <div class="stat-value">{{ profile.followingCount }}</div>
          </div>
          
          <div class="stat-item">
            <label>文章数</label>
            <div class="stat-value">{{ profile.articleCount }}</div>
          </div>
          
          <div class="stat-item">
            <label>总浏览量</label>
            <div class="stat-value">{{ profile.viewCount }}</div>
          </div>
          
          <div class="stat-item">
            <label>总点赞数</label>
            <div class="stat-value">{{ profile.likeCount }}</div>
          </div>
        </div>
      </div>
      
        <div class="form-actions">
          <button class="btn-primary" @click="saveProfile" :disabled="loading" :class="{ 'success-animation': showSaveSuccess }">
            {{ loading ? '保存中...' : showSaveSuccess ? '✅ 保存成功' : '保存修改' }}
          </button>
          <button class="btn-secondary" @click="resetProfile" :disabled="loading">重置</button>
          
          <!-- 保存成功提示条 -->
          <div v-if="showSaveSuccess" class="save-success-banner">
            <span class="success-icon">✅</span>
            <span class="success-text">个人资料已成功保存！</span>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import HeaderComponent from '@/components/HeaderComponent.vue';
import { userAPI } from '@/api/index.js';

export default {
  components: {
    HeaderComponent
  },
  name: 'ProfileSettings',
  props: {
    isLoggedIn: {
      type: Boolean,
      default: false
    },
    userInfo: {
      type: Object,
      default: () => ({})
    },
    showUserPanel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      profile: {
        userAccount: '',
        nickname: '',
        email: '',
        phone: '',
        position: '',
        company: '',
        userProfile: '',
        userAvatar: '',
        location: '',
        website: '',
        githubUrl: '',
        weiboUrl: '',
        juejinPower: 0,
        followerCount: 0,
        followingCount: 0,
        articleCount: 0,
        viewCount: 0,
        likeCount: 0,
        level: 0,
        status: 0,
        emailVerified: 0,
        phoneVerified: 0,
        userRole: '',
        createTime: '',
        lastLogin: ''
      },
      originalProfile: {},
      loading: false,
      showSaveSuccess: false
    }
  },
  mounted() {
    // 只有在用户已登录时才加载数据
    if (this.isLoggedIn) {
      this.loadProfile();
    }
  },
  watch: {
    // 监听登录状态变化
    isLoggedIn(newVal) {
      if (newVal) {
        this.loadProfile();
      } else {
        // 用户登出时清空数据
        this.resetProfileData();
      }
    }
  },
  methods: {
    async loadProfile() {
      // 检查登录状态
      if (!this.isLoggedIn) {
        console.warn('用户未登录，无法获取用户信息');
        this.$message?.warning('请先登录后再查看个人信息');
        return;
      }
      
      try {
        this.loading = true;
        const response = await userAPI.getUserInfo('login');
        
        if (response.code === 0) {
          const userData = response.data;
          console.log('获取到的用户数据:', userData);
          
          this.profile = {
            userAccount: userData.userAccount || '',
            nickname: userData.nickname || '',
            email: userData.email || '',
            phone: userData.phone || '',
            position: userData.position || '',
            company: userData.company || '',
            userProfile: userData.userProfile || '',
            userAvatar: userData.userAvatar || '',
            location: userData.location || '',
            website: userData.website || '',
            githubUrl: userData.githubUrl || '',
            weiboUrl: userData.weiboUrl || '',
            juejinPower: userData.juejinPower || 0,
            followerCount: userData.followerCount || 0,
            followingCount: userData.followingCount || 0,
            articleCount: userData.articleCount || 0,
            viewCount: userData.viewCount || 0,
            likeCount: userData.likeCount || 0,
            level: userData.level || 0,
            status: userData.status || 0,
            emailVerified: userData.emailVerified || 0,
            phoneVerified: userData.phoneVerified || 0,
            userRole: userData.userRole || '',
            createTime: userData.createTime || '',
            lastLogin: userData.lastLogin || ''
          };
          this.originalProfile = { ...this.profile };
          this.$message?.success('用户信息加载成功');
        } else {
          console.error('获取用户信息失败:', response.message);
          this.$message?.error(response.message || '获取用户信息失败');
          
          // 如果是未登录错误，清空数据
          if (response.code === 40100) {
            this.resetProfileData();
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        
        // 处理不同类型的错误
        if (error.response?.status === 401) {
          this.$message?.error('登录已过期，请重新登录');
          this.resetProfileData();
        } else {
          this.$message?.error('网络错误，请稍后重试');
        }
      } finally {
        this.loading = false;
      }
    },
    handleImageError(event) {
      event.target.style.display = 'none';
      this.$message?.warning('头像链接无效，请检查URL是否正确');
    },
    


    async saveProfile() {
      console.log('=== 开始保存用户资料 ===');
      
      // 验证必填字段
      if (!this.profile.nickname?.trim()) {
        this.$message?.error('请输入昵称');
        return;
      }
      
      if (!this.profile.userAvatar?.trim()) {
        this.$message?.error('请输入头像URL');
        return;
      }
      
      try {
        this.loading = true;
        
        // 按照后端接口要求的格式准备数据
        const updateData = {
          company: this.profile.company?.trim() || '',
          githubUrl: this.profile.githubUrl?.trim() || '',
          location: this.profile.location?.trim() || '',
          nickname: this.profile.nickname.trim(),
          position: this.profile.position?.trim() || '',
          userAvatar: this.profile.userAvatar.trim(),
          userProfile: this.profile.userProfile?.trim() || '',
          website: this.profile.website?.trim() || '',
          weiboUrl: this.profile.weiboUrl?.trim() || ''
        };
        
        console.log('准备发送的更新数据:', updateData);
        console.log('调用 /api/user/update/my 接口...');
        
        const response = await userAPI.updateUserInfo(updateData);
        
        console.log('收到服务器响应:', response);
        if (response.code === 0) {
          // 显示更新成功的提示信息
          this.$message?.success({
            message: '✅ 个人资料更新成功！',
            duration: 3000,
            showClose: true
          });
          
          // 更新原始数据
          this.originalProfile = { ...this.profile };
          
          // 显示保存成功的视觉反馈
          this.showSaveSuccess = true;
          setTimeout(() => {
            this.showSaveSuccess = false;
          }, 2000);
          
          // 重新加载用户信息以获取最新数据
          await this.loadProfile();
        } else {
          this.$message?.error({
            message: response.message || '更新失败，请重试',
            duration: 4000,
            showClose: true
          });
        }
      } catch (error) {
        console.error('=== 保存用户资料时发生错误 ===');
        console.error('错误对象:', error);
        console.error('错误消息:', error.message);
        console.error('错误状态码:', error.response?.status);
        console.error('错误状态文本:', error.response?.statusText);
        console.error('错误响应数据:', error.response?.data);
        console.error('错误配置:', error.config);
        
        // 根据错误类型显示不同的提示
        let errorMessage = '更新用户资料失败';
        if (error.code === 'NETWORK_ERROR') {
          errorMessage = '网络连接失败，请检查网络设置';
        } else if (error.response?.status === 401) {
          errorMessage = '登录已过期，请重新登录后再试';
        } else if (error.response?.status === 403) {
          errorMessage = '没有权限修改此信息';
        } else if (error.response?.status >= 500) {
          errorMessage = '服务器错误，请稍后重试';
        } else if (!navigator.onLine) {
          errorMessage = '网络连接失败，请检查网络后重试';
        } else if (error.message.includes('Network Error')) {
          errorMessage = '网络连接失败，请检查后端服务是否启动';
        }
        
        this.$message?.error({
          message: `❌ ${errorMessage}`,
          duration: 5000,
          showClose: true
        });
      } finally {
        this.loading = false;
        console.log('=== 保存操作结束 ===');
      }
    },
    resetProfile() {
      this.profile = { ...this.originalProfile };
      this.$message?.info('已重置为原始数据');
    },
    resetProfileData() {
      // 清空所有用户数据
      this.profile = {
        userAccount: '',
        nickname: '',
        email: '',
        phone: '',
        position: '',
        company: '',
        userProfile: '',
        userAvatar: '',
        location: '',
        website: '',
        githubUrl: '',
        weiboUrl: '',
        juejinPower: 0,
        followerCount: 0,
        followingCount: 0,
        articleCount: 0,
        viewCount: 0,
        likeCount: 0,
        level: 0,
        status: 0,
        emailVerified: 0,
        phoneVerified: 0,
        userRole: '',
        createTime: '',
        lastLogin: ''
      };
      this.originalProfile = {};
    }
  }
}
</script>

<style scoped>
.profile-settings {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-layout {
  display: flex;
  max-width: 1200px;
  margin: 0 auto;
  background-color: white;
  min-height: calc(100vh - 60px);
}

.settings-sidebar {
  width: 250px;
  background-color: #fff;
  border-right: 1px solid #e5e5e5;
  padding: 20px 0;
}

.sidebar-header {
  padding: 0 20px 20px;
  border-bottom: 1px solid #e5e5e5;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.settings-nav {
  list-style: none;
  padding: 0;
  margin: 0;
}

.nav-item {
  margin: 0;
}

.nav-link {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  text-decoration: none;
  color: #666;
  transition: all 0.3s;
}

.nav-link:hover {
  background-color: #f8f9fa;
  color: #007bff;
}

.nav-item.active .nav-link {
  background-color: #e3f2fd;
  color: #007bff;
  border-right: 3px solid #007bff;
}

.nav-icon {
  margin-right: 10px;
  font-size: 16px;
}

.settings-content {
  flex: 1;
  padding: 20px;
  max-width: 800px;
}

.settings-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e5e5;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.settings-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.settings-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.btn-refresh {
  padding: 8px 16px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-refresh:hover:not(:disabled) {
  background-color: #218838;
}

.btn-refresh:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}

.login-prompt {
  text-align: center;
  padding: 60px 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin: 20px 0;
}

.prompt-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.login-prompt h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 20px;
}

.login-prompt p {
  margin: 0 0 30px 0;
  color: #666;
  font-size: 16px;
}

.btn-login {
  padding: 12px 24px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-login:hover {
  background-color: #0056b3;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.form-section h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row .form-group {
  flex: 1;
  margin-bottom: 0;
}

.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row .form-group {
  flex: 1;
  margin-bottom: 0;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.editable-mark {
  color: #1e80ff;
  font-size: 12px;
  font-weight: normal;
}
.form-group input,
.form-group textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #007bff;
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.avatar-preview {
  margin-top: 10px;
}

.avatar-preview img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #ddd;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.form-actions {
  display: flex;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #e5e5e5;
  position: relative;
  flex-wrap: wrap;
  align-items: center;
}

.btn-primary,
.btn-secondary {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
}

/* 只读字段样式 */
input[readonly], textarea[readonly] {
  background-color: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

/* 禁用状态按钮样式 */
button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 保存成功动画 */
.btn-primary.success-animation {
  background-color: #28a745 !important;
  transform: scale(1.05);
  transition: all 0.3s ease;
}

.btn-primary.success-animation:hover {
  background-color: #28a745 !important;
}

/* 保存成功提示条 */
.save-success-banner {
  display: flex;
  align-items: center;
  gap: 8px;
  background: linear-gradient(135deg, #28a745, #20c997);
  color: white;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
  animation: slideInFromRight 0.5s ease-out, fadeOut 0.5s ease-in 1.5s forwards;
  margin-left: auto;
  white-space: nowrap;
}

.success-icon {
  font-size: 16px;
  animation: bounce 0.6s ease-in-out;
}

.success-text {
  font-weight: 500;
}

/* 动画效果 */
@keyframes slideInFromRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
    transform: translateX(0);
  }
  to {
    opacity: 0;
    transform: translateX(20px);
  }
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

/* 加载状态提示 */
.loading-text {
  color: #6c757d;
  font-style: italic;
}

/* 统计数据网格布局 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 10px;
}

.stat-item {
  background: white;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e5e5e5;
  text-align: center;
}

.stat-item label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  font-weight: normal;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #007bff;
}
</style>